<template>
<div class="test">
  <!-- 弹窗 -->
  <el-dialog v-model="store.grantPage"
             :show-close="false"
             append-to-body
             class="dialogClass"
             width="30%"
             draggable overflow
             style="height: 90vh;border-radius: 10px"
             top="5vh"
  >
    <!--弹窗标题-->
    <template #header="{ close, titleId }">
      <div class="dialogHeader">
        <span :id="titleId" class="dlgTitleClass" style="margin: 10px 10px;">角色授权</span>
        <div>
          <el-checkbox v-model="expandAll" @change="toggleExpandAll" label="展开/折叠" size="large" />
          <el-checkbox v-model="checkAll" label="全选/全不选" size="large" />
        </div>
        <el-icon style="font-size: 18px;margin-top: 14px;cursor: pointer" @click="closeDialog()">
          <CloseBold/>
        </el-icon>
      </div>
    </template>
    <template #default style="height: 60vh">
      <el-tree
          class="role-grant"
          ref="treeRef"
          :data="data"
          show-checkbox
          :default-expand-all="expandAll"
          node-key="id"
          highlight-current
          :check-strictly="true"
          :default-checked-keys="checkedKeys"
          :props="defaultProps"
      />
    </template>
    <template #footer>
      <div class="button">
        <el-button  color="#2E5CF6FF" plain @click="closeDialog()">取消</el-button>
        <el-button color="#2E5CF6FF" type="primary" @click="updateGrateMenu()">更新</el-button>
      </div>
    </template>
  </el-dialog>
</div>

</template>


<script setup lang="ts">
import {ArrowLeft, CloseBold} from "@element-plus/icons-vue";

import {defineEmits, ref, watch} from 'vue'
import {roleStore} from "@/stores/role/roleStore.ts";
import {ElMessage, ElMessageBox, type TreeInstance} from "element-plus";
import {grantMenuTree, updateGrate} from "@/api/role";

const emit = defineEmits(['refresh'])
const store = roleStore()
const checkAll = ref(false)
const treeRef = ref<TreeInstance>()
const allIds= ref([] as number[])
const expandAll=ref(true)
//加载数据

watch(() => store.grantRoleId, (newVal) => {
  initTree(newVal)
})

const toggleExpandAll=(type:any)=>{
  if (type) {
    expandAll.value = true;
    Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.expand());
    return;
  }
  expandAll.value = false;
  Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.collapse());
}
const nodes= ref([] as number)
 const getKeys=(data:Tree[])=>{
  data.forEach(item=>{
    nodes.value.push(item.id)
    if(item.children){
      getKeys(item.children)
    }
  })
 }
/**
 * 设置全选或全不选
 */
watch(()=>checkAll.value,(newVal)=>{
  newVal?treeRef.value?.setCheckedKeys(allIds.value):treeRef.value?.setCheckedKeys([])
})

/**
 * 更新授权
 */
const  updateGrateMenu=()=>{
  //确认框
  ElMessageBox.confirm('确认修改角色授权？', '提示', {
    app: undefined, components: undefined, config: undefined, directives: undefined, mixins: [], provides: undefined,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const checkedKeys = treeRef.value?.getCheckedKeys()
    await updateGrate(store.grantRoleId,checkedKeys).then((res) => {
      ElMessage.success("修改授权成功")
    }).catch((e)=>{
      ElMessage.error(e)
    })
    //刷新页面
    closeDialog()
  }).catch(() => {})
}
const data = ref([] as Tree[])
const  checkedKeys = ref([] as number[])
/**
 * 加载数据
 * @param id
 */
const initTree = async (id: number) => {
  await grantMenuTree(id).then((res) => {
    data.value = res.data.grantMenuTree
    checkedKeys.value=res.data.checkedMenuId
    //递归遍历数组，添加所有id
    createAllIds(data.value)
  }).catch((err) => {
    console.log(err)
  })

}
const  createAllIds=(data)=>{
  data.forEach((item) => {
    allIds.value.push(item.id)
    if (item.children) {
      createAllIds(item.children)
    }
  })
  console.log(allIds.value)
}
const resetChecked = () => {
  treeRef.value!.setCheckedKeys([], false)
}

const closeDialog= () => {
  resetChecked()
  store.setGrantPage(false)
  store.setGrantRoleId(0)
  emit("refresh")
}
interface Tree {
  id: number
  title: string
  children?: Tree[]
}
const defaultProps = {
  children: 'children',
  label: 'title',
}

</script>

<style scoped>
.el-dialog .el-dialog__header {
  margin: 0 !important;
  padding: 0 !important;
}

.el-dialog .dialogHeader {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 40px;
  margin: 0 10px;
  font-size: 18px;
  font-weight: bolder;
}

/* 确保对话框主体可以使用flex布局 */
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  padding: 0 50px!important;
  height: 70px!important;
}

.role-grant {
  height: 70vh;
  overflow: auto;
}

.el-dialog .el-dialog__footer {
  padding: 10px;
}

/* 确保对话框整体高度生效 */
:deep(.el-dialog) {
  height: 500px !important; /* 设置对话框总高度 */
}

.button{
  margin: 10px 10px;
  .el-button{
    width: 80px;
  }
}
</style>


